﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
using BaHuan.Utils;

namespace BaHuan
{
    public partial class FrmPhieuHangTra : Form
    {
        private KhachHangManagement khachhangMgt = new KhachHangManagement();
        private ChiNhanhKhachHangManagement chinhanhkhachangMgt = new ChiNhanhKhachHangManagement();
        private ChiNhanhCongTyMgt chinhanhctyMgt = new ChiNhanhCongTyMgt();
        private CTPhieuXuatHangManagement ctphieuxuathangMgt = new CTPhieuXuatHangManagement();
        private HangHoaManagement hanghoaMgt = new HangHoaManagement();
        private KhayDungManagement khaydungMgt = new KhayDungManagement();
        private PhieuXuatHangManagement phieuxuathangMgt = new PhieuXuatHangManagement();
        private PhieuHangTraManagement phieuhangtraMgt = new PhieuHangTraManagement();
        private CTPhieuHangTraManagement ctphieuhangtraMgt = new CTPhieuHangTraManagement();
        private KhoManagement khoMgt = new KhoManagement();
        private QuanLyKhoManagement quanlykhoMgt = new QuanLyKhoManagement();
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private DonViTinhMgt donvitinhMgt = new DonViTinhMgt();
        private BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();

        private List<CTPhieuHangTra> CTPhieuHangTraNeedDelete = new List<CTPhieuHangTra>();

        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private int idLoaiPhieu = 5;
        private bool IsEdited = false;
        private int iOldId = 0;
        private string sOldNoiNhan = "";

        private PhieuHangTra mphieuhangtra;
        private PhieuXuatHang mphieuxuathang;

        private NhanVien nhanvien;
        public NhanVien NhanVien
        {
            set { this.nhanvien = value; }
            get { return this.nhanvien; }
        }

        public FrmPhieuHangTra(PhieuXuatHang phieuxuathang)
        {
            InitializeComponent();
            this.mphieuxuathang = phieuxuathang;
            LoadAll();
        }

        public FrmPhieuHangTra(PhieuHangTra phieuhangtra)
        {
            InitializeComponent();
            btnLuu.Enabled = false;
            this.mphieuhangtra = phieuhangtra;
            btnDinhKhoan.Enabled = true;
            btnSua.Enabled = true;
            btnXoa.Enabled = true;

            dgvChiTiet.Enabled = false;
            dgvChiTiet.AutoGenerateColumns = false;

            BindingToCbo();

            dtOld = this.mphieuhangtra.NgayThang;
            dtpNgay.Value = this.mphieuhangtra.NgayThang;

            prefixOld = this.mphieuhangtra.Prefix;
            cboPrefix.Text = this.mphieuhangtra.Prefix;
            txtMaSo.Text = this.mphieuhangtra.OrderNumber;

            txtSoChungTu.Text = this.mphieuhangtra.SoChungTu;
            txtDiaChi.Text = this.mphieuhangtra.DiaChi;
            txtNguoiLapPhieu.Text = this.mphieuhangtra.NguoiLapPhieu;
            txtTongTienHang.Text = this.mphieuhangtra.TongTienHang.ToString();
            txtTienChietKhau.Text = this.mphieuhangtra.TienChietKhau.ToString();
            txtTienVAT.Text = this.mphieuhangtra.TienThue.ToString();
            lblChietKhau.Text = this.mphieuhangtra.ChietKhau.ToString();
            lblVAT.Text = this.mphieuhangtra.Thue.ToString();
            txtTongCong.Text = this.mphieuhangtra.TongCong.ToString();

            cboKho.SelectedValue = this.mphieuhangtra.IdChiNhanhCongTy;
            cboKhachHang.SelectedIndex = cboKhachHang.FindString(this.mphieuhangtra.KhachHang);
            cboChiNhanhKhachHang.SelectedIndex = cboChiNhanhKhachHang.FindString(this.mphieuhangtra.ChiNhanhKhachHang);

            List<CTPhieuHangTra> lstCTPhieuHangTra = (from ctpx in GetAllCTPhieuHangTra()
                                                      where ctpx.IdPhieuHangTra == mphieuhangtra.Id
                                                      select ctpx).ToList();

            for (int i = 0; i < lstCTPhieuHangTra.Count; i++)
            {
                DataGridViewRow row = new DataGridViewRow();

                DataGridViewComboBoxCell cboCell = new DataGridViewComboBoxCell();
                List<HangHoa> lstHangThanhPham = GetAllHangHoa();
                cboCell.DataSource = lstHangThanhPham;
                cboCell.DisplayMember = "Ten";
                cboCell.ValueMember = "MaSo";
                cboCell.Value = lstCTPhieuHangTra[i].MaHang;
                row.Cells.Add(cboCell);

                DataGridViewCell cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].MaHang;
                row.Cells.Add(cell);

                cboCell = new DataGridViewComboBoxCell();
                cboCell.DataSource = GetAllDonViTinh();
                cboCell.DisplayMember = "TenDVT";
                cboCell.ValueMember = "TenDVT";
                cboCell.Value = lstCTPhieuHangTra[i].DonViTinh;
                row.Cells.Add(cboCell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].SoLuong;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].DonGia;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].ThanhTien;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].SoKg;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].DonViTinhQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].SoLuongQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuHangTra[i].Id;
                row.Cells.Add(cell);

                dgvChiTiet.Rows.Add(row);
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (txtMaSo.Text == "")
            {
                MessageBox.Show("Vui lòng chọn mã phiếu");
                return;
            }

            if (dgvChiTiet.Rows.Count >= 1)
            {
                ResultObj resultObj = new ResultObj();

                mphieuhangtra = new PhieuHangTra();
                mphieuhangtra.MaSo = cboPrefix.Text + "/" + dtpNgay.Value.ToString("MM") + dtpNgay.Value.ToString("yy") + "/" + txtMaSo.Text;
                mphieuhangtra.History = "";
                mphieuhangtra.NgayThang = dtpNgay.Value;
                mphieuhangtra.NguoiLapPhieu = txtNguoiLapPhieu.Text;
                mphieuhangtra.KhachHang = ((KhachHang)cboKhachHang.SelectedItem).Ten;
                mphieuhangtra.ChiNhanhKhachHang = cboChiNhanhKhachHang.SelectedValue != null ? ((ChiNhanhKhachHang)cboChiNhanhKhachHang.SelectedItem).Ten : "";
                mphieuhangtra.DiaChi = txtDiaChi.Text;
                mphieuhangtra.IdChiNhanhCongTy = Convert.ToInt32(cboKho.SelectedValue.ToString());
                mphieuhangtra.TongTienHang = Convert.ToInt64(txtTongTienHang.Text);
                mphieuhangtra.ChietKhau = Convert.ToInt64(lblChietKhau.Text);
                mphieuhangtra.TienChietKhau = Convert.ToInt64(txtTienChietKhau.Text);
                mphieuhangtra.Thue = Convert.ToInt64(lblVAT.Text);
                mphieuhangtra.TienThue = Convert.ToInt64(txtTienVAT.Text);
                mphieuhangtra.TongCong = Convert.ToInt64(txtTongCong.Text);
                mphieuhangtra.SoChungTu = txtSoChungTu.Text;
                mphieuhangtra.LyDo = txtLyDo.Text;

                if (!IsEdited)
                {
                    resultObj = phieuhangtraMgt.SaveNewPhieuHangTra(mphieuhangtra);
                    lblId.Text = resultObj.ReturnCode.ToString();

                    for (int i = 0; i < dgvChiTiet.Rows.Count; i++)
                    {                        
                        CTPhieuHangTra ctphieuhangtra = new CTPhieuHangTra();
                        ctphieuhangtra.IdPhieuHangTra = Convert.ToInt32(lblId.Text);
                        ctphieuhangtra.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                        ctphieuhangtra.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                        ctphieuhangtra.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                        ctphieuhangtra.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                        ctphieuhangtra.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                        ctphieuhangtra.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                        ctphieuhangtra.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                        ctphieuhangtra.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                        ctphieuhangtra.SoKg = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].Value.ToString());

                        resultObj = ctphieuhangtraMgt.SaveNewCTPhieuHangTra(ctphieuhangtra);
                        dgvChiTiet.Rows[i].Cells[9].Value = resultObj.ReturnCode;
                    }
                }
                else
                {
                    List<CTPhieuHangTra> lst = (from p in GetAllCTPhieuHangTra()
                                                where p.IdPhieuHangTra == iOldId
                                                select p).ToList();

                    List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                    where q.SoChungTuNhap == mphieuhangtra.MaSo
                                                    select q).ToList();

                    if (lstQuanLykho.Count > 0)
                    {
                        foreach (QuanLyKho q in lstQuanLykho)
                        {
                            q.IsDelete = 1;
                            resultObj = quanlykhoMgt.UpdateQuanLyKho(q);

                            HangHoa hanghoa = (from h in GetAllHangHoa()
                                               where h.Id == q.IdHangHoa && h.NoiLuuTru == sOldNoiNhan
                                               select h).FirstOrDefault();

                            int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                            hanghoa.SoLuong += lst[index].SoLuong;
                            resultObj = hanghoaMgt.UpdateHangHoa(hanghoa);
                        }
                    }

                    mphieuhangtra.Id = Convert.ToInt32(lblId.Text);
                    resultObj = phieuhangtraMgt.UpdatePhieuHangTra(mphieuhangtra);
                    
                    for (int i = 0; i < dgvChiTiet.Rows.Count; i++)
                    {
                        CTPhieuHangTra ctphieuhangtra = new CTPhieuHangTra();
                        ctphieuhangtra.IdPhieuHangTra = mphieuhangtra.Id;
                        ctphieuhangtra.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                        ctphieuhangtra.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                        ctphieuhangtra.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                        ctphieuhangtra.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                        ctphieuhangtra.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                        ctphieuhangtra.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                        ctphieuhangtra.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                        ctphieuhangtra.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                        ctphieuhangtra.SoKg = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].Value.ToString());

                        if (dgvChiTiet.Rows[i].Cells[6].Value != null)
                        {
                            ctphieuhangtra.Id = Convert.ToInt32(dgvChiTiet.Rows[i].Cells[9].Value.ToString());
                            resultObj = ctphieuhangtraMgt.UpdateCTPhieuHangTra(ctphieuhangtra);
                        }
                        else
                        {
                            resultObj = ctphieuhangtraMgt.SaveNewCTPhieuHangTra(ctphieuhangtra);
                            dgvChiTiet.Rows[i].Cells[9].Value = resultObj.ReturnCode;
                        }

                        resultObj = ctphieuhangtraMgt.UpdateCTPhieuHangTra(ctphieuhangtra);
                    }                    
                }

                if (resultObj.ReturnCode > 0)
                {
                    MessageBox.Show("Lưu thành công", "Thông báo");
                    if (!IsEdited)
                    {
                        btnSua.Enabled = true;

                        //***insert quan ly kho cho Phieu Hang Tra
                        List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                        where q.SoChungTuNhap == mphieuhangtra.MaSo
                                                        select q).ToList();

                        if (lstQuanLykho.Count <= 0)
                        {
                            ResultObj resObj = new ResultObj();

                            List<Kho> lstKho = (from k in GetAllKho()
                                                where k.TenKho == "155"
                                                select k).ToList();

                            for (int i = 0; i < dgvChiTiet.Rows.Count; i++)
                            {
                                string maso = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                                List<HangHoa> lstHangHoa = (from h in GetAllHangHoa()
                                                            where h.MaSo == maso
                                                            select h).ToList();
                                if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                {
                                    QuanLyKho quanlykho = new QuanLyKho();
                                    quanlykho.IdKho = lstKho[0].Id;
                                    quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                    quanlykho.SoChungTuNhap = mphieuhangtra.MaSo;
                                    quanlykho.SoChungTuXuat = "";

                                    resObj = quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                }
                            }
                        }
                    }

                    IsEdited = false;

                    if (CTPhieuHangTraNeedDelete.Count > 0)
                    {
                        foreach (CTPhieuHangTra ct in CTPhieuHangTraNeedDelete)
                        {
                            ct.IsDelete = 1;
                            ctphieuhangtraMgt.UpdateCTPhieuHangTra(ct);
                        }
                        CTPhieuHangTraNeedDelete.Clear();
                    }

                    dgvChiTiet.Enabled = false;
                    gpbThongTin.Enabled = false;

                    btnLuu.Enabled = false;
                    btnDinhKhoan.Enabled = true;
                    btnSua.Enabled = true;
                    btnXoa.Enabled = true;
                }
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            IsEdited = true;
            dtpNgay.Select();

            dgvChiTiet.Enabled = true;
            gpbThongTin.Enabled = true;

            btnLuu.Enabled = true;
            btnDinhKhoan.Enabled = false;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("Bạn có chắc chắn muốn xóa chứng từ này không?", "Xóa phiếu hàng trả", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                ResultObj resultObj = new ResultObj();

                PhieuHangTra phieuhangtra = new PhieuHangTra();
                phieuhangtra.MaSo = txtMaSo.Text;
                phieuhangtra.NgayThang = dtpNgay.Value;
                phieuhangtra.SoChungTu = txtSoChungTu.Text;
                phieuhangtra.NguoiLapPhieu = txtNguoiLapPhieu.Text;
                phieuhangtra.KhachHang = (cboKhachHang.Text != "" ? ((KhachHang)cboKhachHang.SelectedItem).Ten : "");
                phieuhangtra.ChiNhanhKhachHang = (cboChiNhanhKhachHang.Text != "" ? ((ChiNhanhKhachHang)cboChiNhanhKhachHang.SelectedItem).Ten : "");
                phieuhangtra.LyDo = txtLyDo.Text;
                phieuhangtra.DiaChi = txtDiaChi.Text;
                phieuhangtra.IdChiNhanhCongTy = ((ChiNhanhCongTy)cboKho.SelectedItem).Id;
                phieuhangtra.TongTienHang = Convert.ToInt64(txtTongTienHang.Text);
                phieuhangtra.ChietKhau = Convert.ToInt64(lblChietKhau.Text);
                phieuhangtra.TienChietKhau = Convert.ToInt64(txtTienChietKhau.Text);
                phieuhangtra.Thue = Convert.ToInt64(lblVAT.Text);
                phieuhangtra.TienThue = Convert.ToInt64(txtTienVAT.Text);
                phieuhangtra.TongCong = Convert.ToInt64(txtTongCong.Text);
                phieuhangtra.IsDelete = 1;
                phieuhangtra.Id = Convert.ToInt32(lblId.Text);

                resultObj = phieuhangtraMgt.UpdatePhieuHangTra(phieuhangtra);

                List<CTPhieuHangTra> lst = (from p in GetAllCTPhieuHangTra()
                                              where p.IdPhieuHangTra == phieuhangtra.Id
                                              select p).ToList();

                foreach (CTPhieuHangTra ct in lst)
                {
                    ct.IsDelete = 1;
                    resultObj = ctphieuhangtraMgt.UpdateCTPhieuHangTra(ct);
                }

                EditOrRemoveDinhKhoan(phieuhangtra.MaSo);

                List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                where q.SoChungTuXuat == phieuhangtra.MaSo
                                                select q).ToList();

                if (lstQuanLykho.Count > 0)
                {
                    foreach (QuanLyKho q in lstQuanLykho)
                    {
                        q.IsDelete = 1;
                        resultObj = quanlykhoMgt.UpdateQuanLyKho(q);

                        HangHoa hanghoa = (from h in GetAllHangHoa()
                                           where h.Id == q.IdHangHoa && h.NoiLuuTru == ((ChiNhanhCongTy)cboKho.SelectedItem).TenChiNhanh
                                           select h).FirstOrDefault();

                        int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                        hanghoa.SoLuong -= lst[index].SoLuong;
                        resultObj = hanghoaMgt.UpdateHangHoa(hanghoa);
                    }
                }

                MessageBox.Show("Đã xóa", "Thông báo!");
                this.Close();
            }
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            FrmDinhKhoanPhieuHangTra frmDinhKhoanPhieuHangTra = new FrmDinhKhoanPhieuHangTra();
            frmDinhKhoanPhieuHangTra.PhieuHangTra = this.mphieuhangtra;
            frmDinhKhoanPhieuHangTra.Show();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void BindingToCbo()
        {
            cboKho.DataSource = GetAllChiNhanhCongTy();
            cboKho.DisplayMember = "TenChiNhanh";
            cboKho.ValueMember = "Id";

            cboKhachHang.DataSource = GetAllKhachHang();
            cboKhachHang.DisplayMember = "Ten";
            cboKhachHang.ValueMember = "Id";

            cboChiNhanhKhachHang.DataSource = GetAllChiNhanhKhachHang();
            cboChiNhanhKhachHang.DisplayMember = "Ten";
            cboChiNhanhKhachHang.ValueMember = "Id";

            cboPrefix.DataSource = GetAllBangMaPhieu(idLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";
        }

        public void LoadAll()
        {
            btnDinhKhoan.Enabled = true;
            btnSua.Enabled = true;
            btnXoa.Enabled = true;

            dgvChiTiet.Enabled = false;
            dgvChiTiet.AutoGenerateColumns = false;

            BindingToCbo();
                        
            txtSoChungTu.Text = this.mphieuxuathang.MaSo;
            txtDiaChi.Text = this.mphieuxuathang.DiaChi;
            txtNguoiLapPhieu.Text = this.mphieuxuathang.NguoiLap;
            txtTongTienHang.Text = this.mphieuxuathang.TongTienHang.ToString();
            txtTienChietKhau.Text = this.mphieuxuathang.TienChietKhau.ToString();
            txtTienVAT.Text = this.mphieuxuathang.TienVAT.ToString();
            lblChietKhau.Text = this.mphieuxuathang.ChietKhau.ToString();
            lblVAT.Text = this.mphieuxuathang.VAT.ToString();
            txtTongCong.Text = this.mphieuxuathang.TongCong.ToString();

            cboKho.SelectedValue = mphieuxuathang.IdChiNhanhCongTy;
            cboKhachHang.SelectedIndex = cboKhachHang.FindString(this.mphieuxuathang.KhachHang);
            cboChiNhanhKhachHang.SelectedIndex = cboChiNhanhKhachHang.FindString(this.mphieuxuathang.ChiNhanhKhachHang);

            List<CTPhieuXuatHang> lstCTPhieuXuatHang = (from ctpx in GetAllCTPhieuXuatHang()
                                                        where ctpx.IdPhieuXuatHang == mphieuxuathang.Id
                                                        select ctpx).ToList();

            for (int i = 0; i < lstCTPhieuXuatHang.Count; i++)
            {
                DataGridViewRow row = new DataGridViewRow();

                DataGridViewComboBoxCell cboCell = new DataGridViewComboBoxCell();
                List<HangHoa> lstHangThanhPham = GetAllHangHoa();
                cboCell.DataSource = lstHangThanhPham;
                cboCell.DisplayMember = "Ten";
                cboCell.ValueMember = "MaSo";
                cboCell.Value = lstCTPhieuXuatHang[i].MaHang;
                row.Cells.Add(cboCell);

                DataGridViewCell cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].MaHang;
                row.Cells.Add(cell);

                cboCell = new DataGridViewComboBoxCell();
                cboCell.DataSource = GetAllDonViTinh();
                cboCell.DisplayMember = "TenDVT";
                cboCell.ValueMember = "TenDVT";
                cboCell.Value = lstCTPhieuXuatHang[i].DonViTinh;
                row.Cells.Add(cboCell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].SoLuong;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].DonGia;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].ThanhTien;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].SoKG;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].DonViTinhQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].SoLuongQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].Id;
                row.Cells.Add(cell);

                dgvChiTiet.Rows.Add(row);
            }
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        private void dgvChiTiet_Enter(object sender, EventArgs e)
        {
            if (dgvChiTiet.CurrentRow != null)
            {
                dgvChiTiet.CurrentCell = dgvChiTiet.Rows[dgvChiTiet.CurrentRow.Index].Cells[0];
            }
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgay.Value);
        }

        private void dtpNgay_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtpNgay.Value)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgay.Value);
        }

        private void dgvChiTiet_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void dgvChiTiet_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                if (e.ColumnIndex == 2)
                {
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                    {
                        MessageBox.Show("Vui lòng chọn đơn vị tính !", "Thông báo");
                        return;
                    }
                }

                if (e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6)
                {
                    long num;
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                        dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                    if (!Int64.TryParse(dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out num))
                    {
                        MessageBox.Show("Vui lòng nhập số !", "Thông báo");
                        dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                        return;
                    }
                }

                if (e.ColumnIndex == 3 || e.ColumnIndex == 4)
                {
                    long soluong = 0;
                    long dongia = 0;

                    if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value != null)
                    {
                        if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString() != "")
                        {
                            soluong = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString());
                            if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "cây")
                                dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = (soluong * 300).ToString();
                            else if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "khay")
                            {
                                List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                            where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[1].Value.ToString()
                                                            select htp).ToList();
                                List<KhayDung> lstKhayDung = (from kd in GetAllKhayDung()
                                                              where kd.Id == lstHangHoa[0].IdKhayDung
                                                              select kd).ToList();
                                dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = (lstKhayDung[0].SoLuongHop * soluong).ToString();
                            }
                            else
                                dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString();
                        }
                        else
                        {
                            soluong = 0;
                            dgvChiTiet.Rows[e.RowIndex].Cells[3].Value = "0";
                        }
                    }

                    dongia = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[4].Value.ToString());
                    long thanhtien = soluong * dongia;
                    dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = thanhtien.ToString();

                    long tongthanhtienBaoBi = 0;
                    long tongthanhpham = 0;
                    long chietkhau = 0;
                    long vat = 0;
                    long tongcong = 0;

                    for (int i = 0; i < dgvChiTiet.Rows.Count; i++)
                    {
                        string sCompare = dgvChiTiet.Rows[i].Cells[1].Value.ToString().Substring(0, 1).ToLower();
                        if (sCompare == "8" || sCompare == "9" || sCompare == "b")
                        {
                            tongthanhtienBaoBi += Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                        }
                        else
                        {
                            tongthanhpham += Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                        }
                    }

                    txtTongTienHang.Text = tongthanhpham.ToString();
                    txtTienBaoBi.Text = tongthanhtienBaoBi.ToString();
                    chietkhau = tongthanhpham * Convert.ToInt64(lblChietKhau.Text) / 100;
                    txtTienChietKhau.Text = chietkhau.ToString();
                    vat = (tongthanhpham * Convert.ToInt64(lblVAT.Text) - Convert.ToInt64(txtTienChietKhau.Text)) / 100;
                    txtTienVAT.Text = vat.ToString();
                    tongcong = (tongthanhpham + vat + tongthanhtienBaoBi) - chietkhau;
                    txtTongCong.Text = tongcong.ToString();
                }

                if (e.ColumnIndex == 2)
                {
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "khay")
                        dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = "Hộp";
                    else if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "cây")
                        dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = "Quả";
                    else
                        dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString();
                }

                if (e.ColumnIndex == 0)
                {
                    dgvChiTiet.Rows[e.RowIndex].Cells[1].Value = dgvChiTiet.Rows[e.RowIndex].Cells[0].Value.ToString();

                    HangHoa hanghoa = (from htp in GetAllHangHoa()
                                       where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[0].Value.ToString()
                                       select htp).FirstOrDefault();

                    if (hanghoa.Id != - 1)
                        dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = hanghoa.DonGia;
                }

                if (e.ColumnIndex == 1)
                {
                    HangHoa hanghoa = (from htp in GetAllHangHoa()
                                       where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[1].Value.ToString()
                                       select htp).FirstOrDefault();

                    if (hanghoa.Id != -1)
                    {
                        dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = hanghoa.DonGia;
                        dgvChiTiet.Rows[e.RowIndex].Cells[0].Value = hanghoa.MaSo;
                    }
                }
            }
        }

        private void cboKho_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboKho.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboKho.Text) && cboKho.Text != "")
                {
                    cboKho.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKho.SelectedValue == null)
            {
                cboKho.Text = "";
                cboKho.Focus();
            }
        }

        private void cboKhachHang_Leave(object sender, EventArgs e)
        {
            foreach (KhachHang b in cboKhachHang.Items)
            {
                if (b.Ten.ToLower().Contains(cboKhachHang.Text) && cboKhachHang.Text != "")
                {
                    cboKhachHang.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKhachHang.SelectedValue == null)
            {
                cboKhachHang.Text = "";
                cboKhachHang.Focus();
            }
        }

        private void cboChiNhanhKhachHang_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhKhachHang b in cboChiNhanhKhachHang.Items)
            {
                if (b.Ten.ToLower().Contains(cboChiNhanhKhachHang.Text) && cboChiNhanhKhachHang.Text != "")
                {
                    cboChiNhanhKhachHang.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboChiNhanhKhachHang.SelectedValue == null)
            {
                cboChiNhanhKhachHang.Text = "";
            }
        }

        private void cboChiNhanhKhachHang_SelectedValueChanged(object sender, EventArgs e)
        {
            ChiNhanhKhachHang chinhanhkhachhang = (from c in GetAllChiNhanhKhachHang()
                                                   where c.Id == ((ChiNhanhKhachHang)cboChiNhanhKhachHang.SelectedItem).Id
                                                   select c).FirstOrDefault();

            txtDiaChi.Text = chinhanhkhachhang.DiaChi;
        }

        private void cboKhachHang_SelectedValueChanged(object sender, EventArgs e)
        {
            KhachHang khachhang = (from c in GetAllKhachHang()
                                   where c.Id == ((KhachHang)cboKhachHang.SelectedItem).Id
                                   select c).FirstOrDefault();

            txtDiaChi.Text = khachhang.DiaChi;
        }

        private void dgvChiTiet_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvChiTiet.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvChiTiet.ClearSelection();
                    dgvChiTiet.CurrentCell = dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvChiTiet.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvChiTiet.CurrentRow != null)
            {
                if (dgvChiTiet.CurrentRow.Index != (dgvChiTiet.Rows.Count - 1))
                    dgvChiTiet.Rows.RemoveAt(dgvChiTiet.CurrentRow.Index);
                if (dgvChiTiet.CurrentRow.Cells[9] != null)
                {
                    int id = Convert.ToInt32(dgvChiTiet.CurrentRow.Cells[9].Value.ToString());

                    CTPhieuHangTra ctPhieuHangTra = (from ct in GetAllCTPhieuHangTra()
                                                     where ct.Id == id
                                                     select ct).FirstOrDefault();

                    if (ctPhieuHangTra != null)
                    {
                        if (!CTPhieuHangTraNeedDelete.Contains(ctPhieuHangTra))
                            CTPhieuHangTraNeedDelete.Add(ctPhieuHangTra);
                    }
                }
            }
        }

        public List<DonViTinh> GetAllDonViTinh()
        {
            ResultObj resultObj = new ResultObj();
            List<DonViTinh> lstDVT = new List<DonViTinh>();

            resultObj = donvitinhMgt.GetAllDonViTinh();
            lstDVT = (List<DonViTinh>)resultObj.Result;

            return lstDVT;
        }

        public List<KhachHang> GetAllKhachHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khachhangMgt.GetAllKhachHang();
            List<KhachHang> listKhachHang = (List<KhachHang>)resultObj.Result;

            return listKhachHang;
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhctyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> listChiNhanhCongTy = (List<ChiNhanhCongTy>)resultObj.Result;

            return listChiNhanhCongTy;
        }

        public List<ChiNhanhKhachHang> GetAllChiNhanhKhachHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhkhachangMgt.GetAllChiNhanhKhachHang();
            List<ChiNhanhKhachHang> listChiNhanhKhachHang = (List<ChiNhanhKhachHang>)resultObj.Result;

            return listChiNhanhKhachHang;
        }

        public List<CTPhieuXuatHang> GetAllCTPhieuXuatHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = ctphieuxuathangMgt.GetAllCTPhieuXuatHang();
            List<CTPhieuXuatHang> listCTPhieuXuatHang = (List<CTPhieuXuatHang>)resultObj.Result;

            return listCTPhieuXuatHang;
        }

        public List<CTPhieuHangTra> GetAllCTPhieuHangTra()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = ctphieuhangtraMgt.GetAllCTPhieuHangTra();
            List<CTPhieuHangTra> listCTPhieuHangTra = (List<CTPhieuHangTra>)resultObj.Result;

            return listCTPhieuHangTra;
        }

        public List<HangHoa> GetAllHangHoa()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> listHangHoa = (List<HangHoa>)resultObj.Result;

            return listHangHoa;
        }

        public List<KhayDung> GetAllKhayDung()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khaydungMgt.GetAllKhayDung();
            List<KhayDung> listKhayDung = (List<KhayDung>)resultObj.Result;

            return listKhayDung;
        }

        public List<PhieuXuatHang> GetAllPhieuXuatHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = phieuxuathangMgt.GetAllPhieuXuatHang();
            List<PhieuXuatHang> listPhieuXuatHang = (List<PhieuXuatHang>)resultObj.Result;

            return listPhieuXuatHang;
        }

        public List<Kho> GetAllKho()
        {
            ResultObj resultObj = new ResultObj();
            List<Kho> lstKho = new List<Kho>();

            resultObj = khoMgt.GetAllKho();
            lstKho = (List<Kho>)resultObj.Result;

            return lstKho;
        }

        public List<QuanLyKho> GetAllQuanLyKho()
        {
            ResultObj resultObj = new ResultObj();
            List<QuanLyKho> lstQuanLyKho = new List<QuanLyKho>();

            resultObj = quanlykhoMgt.GetAllQuanLyKho();
            lstQuanLyKho = (List<QuanLyKho>)resultObj.Result;

            return lstQuanLyKho;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }
    }
}
